import logging
import os
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask.logging import default_handler

from web.DbHandler import DbHandler


def gen_log_file(log_file='sim.log') -> str:
    log_dir = 'log'
    home = os.environ.get('HOME_EXT')
    if not home:
        home = os.environ.get('HOME')
    if home:
        log_dir = os.path.join(home, log_dir)
        if not os.path.exists(log_dir):
            # 多Worker启动，可能触发异常
            os.makedirs(log_dir, exist_ok=True)
    return os.path.join(log_dir, log_file)


def config_log(app: Flask):
    """
    配置 默认 日志
    :param app:
    :return:
    """
    app.logger.removeHandler(default_handler)
    # 清除 默认handler
    if app.logger.root:
        app.logger.root.handlers.clear()
    app.logger.setLevel(logging.DEBUG)

    # Log
    formatter = logging.Formatter(
        '[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(process)d-%(thread)d] - %(message)s')
    # Stream Handler
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    stream_handler.setFormatter(formatter)
    # File Handler
    logfile = gen_log_file()
    time_file_handler = RotatingFileHandler(logfile, maxBytes=1024 * 1024 * 10, backupCount=10)
    time_file_handler.setLevel(logging.DEBUG)
    time_file_handler.setFormatter(formatter)
    time_file_handler.suffix = '%Y%m%d_%H.log'
    # App Handler Config
    app.logger.addHandler(stream_handler)
    app.logger.addHandler(time_file_handler)
    # app.logger.addHandler(DbHandler('biz'))
    # add sqlalchemy to file
    logging.getLogger('sqlalchemy').addHandler(time_file_handler)
    #
    app.logger.info('[INIT] DEFAULT log file: %s', logfile)


def config_web_log(app: Flask):
    """
    配置 WEB 日志
    :param app:
    :return:
    """
    web_logger = logging.getLogger("WebLogger")
    web_logger.setLevel(logging.DEBUG)
    app.web_logger = web_logger

    # Log
    formatter = logging.Formatter(
        '[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(process)d-%(thread)d] - %(message)s')
    # Stream Handler
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    stream_handler.setFormatter(formatter)
    # File Handler
    logfile = gen_log_file('web.log')
    time_file_handler = RotatingFileHandler(logfile, maxBytes=1024 * 1024 * 10, backupCount=10)
    time_file_handler.setLevel(logging.DEBUG)
    time_file_handler.setFormatter(formatter)
    time_file_handler.suffix = '%Y%m%d_%H.log'
    # App Handler Config
    app.web_logger.addHandler(stream_handler)
    app.web_logger.addHandler(time_file_handler)
    app.web_logger.addHandler(DbHandler('web'))
    #
    app.logger.info('[INIT] WEB log file: %s', logfile)
